<template>
  <div class="register">
    <div class="register-top">
      <van-icon name="arrow-left" @click="$router.push({name:'Login'})" />
      <h2>手机号注册</h2>
    </div>

    <div class="register-register">
      <van-cell-group>
        <van-field placeholder="请输入手机号" v-model="iphoneNum" />
      </van-cell-group>
      <van-cell-group>
        <van-field placeholder="请输入短信验证码" v-model="value" @blur="affirm">
          <van-button
            class="yanzheng"
            slot="button"
            size="small"
            type="default"
            @click="changeYzm"
          >验证码：{{str}}</van-button>
        </van-field>
        <van-cell-group>
          <van-field placeholder="请设置登录密码" v-model="passWord" type="password" />
        </van-cell-group>
        <van-button class="shouji" round type="info" @click="clickHandle">注册</van-button>
      </van-cell-group>
      <span class="register-span1">
        邮箱注册
        <van-icon name="arrow" />
      </span>
    </div>
    <!-- register-register  end -->
  </div>
</template>
<script>
// let flag = 0;
import axios from "axios";
export default {
  data() {
    return {
      iphoneNum: "",
      passWord: "",
      value: "",
      list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
      str: ""
    };
  },
  created() {
    for (var i = 0; i <= 3; i++) {
      const a = Math.floor(Math.random() * this.list.length);
      this.str += a;
    }
  },
  methods: {
    changeYzm() {
      this.str = "";
      for (var i = 0; i <= 3; i++) {
        const a = Math.floor(Math.random() * this.list.length);
        this.str += a;
      }
    },
    clickHandle() {
      if (this.iphoneNum && this.passWord) {
        axios
          .post("http://192.168.17.95:3000/api/v1/flowerslr/regist", {
            username: this.iphoneNum,
            password: this.passWord
          })
          .then(res => {
            if (res.data.code == "success") {
              console.log(res.data.code);
              this.$toast("注册成功");
              this.$router.push({ name: "Login" });
            } else if (res.data.code == "error") {
              this.$toast("注册失败,用户名已存在");
              console.log(res.data.code);
              this.iphoneNum = "";
              this.passWord = "";
              this.value = "";
              this.changeYzm()
            }
          });
      } else {
        this.$toast("请输入用户名和密码");
      }
    },
    affirm() {
      if (this.value == this.str) {
        this.$toast("验证码输入正确");
      } else {
        this.$toast("验证码输入错误");
      }
    }
  }
};
</script>
<style scoped>
@import "../css/register.css";
</style>